package com.lkd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.google.common.collect.Lists;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.dao.NodeDao;
import com.lkd.entity.BusinessTypeEntity;
import com.lkd.entity.NodeEntity;
import com.lkd.entity.RegionEntity;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.exception.LogicException;
import com.lkd.http.controller.vo.NodeReq;
import com.lkd.service.BusinessTypeService;
import com.lkd.service.NodeService;
import com.lkd.service.RegionService;
import com.lkd.service.VendingMachineService;
import com.lkd.vo.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NodeServiceImpl extends ServiceImpl<NodeDao, NodeEntity> implements NodeService {


    @Autowired
    private RegionService regionService;

    @Autowired
    private BusinessTypeService businessTypeService;

    @Autowired
    private VendingMachineService vendingMachineService;

    @Override
    public Pager<NodeEntity> search(Long pageIndex, Long pageSize, String name, Long regionId) {
        // 先构建MP分页查询
        Page<NodeEntity> p1 = new Page<>(pageIndex, pageSize);

        // LambdaQueryWrapper<NodeEntity> qw = new LambdaQueryWrapper<>() ;
        // 构建查询条件
        LambdaQueryWrapper<NodeEntity> qw = Wrappers.lambdaQuery();
        // 名称模糊查询
        qw.like(StrUtil.isNotBlank(name), NodeEntity::getName, name);
        // 区域id精确查询
        qw.eq(ObjectUtil.isNotNull(regionId), NodeEntity::getRegionId, regionId);

        // 根据创建时间倒序
        qw.orderByDesc(NodeEntity::getCreateTime);

        p1 = page(p1, qw);  //分页后的结果
        // 联查出区域对象  "regionId": "1",
        // 联查出商圈对象  "businessId": 1,
        // 联查此点位下的售货机数据量  SELECT  COUNT(*) FROM tb_vending_machine WHERE node_id=?
        p1.getRecords().forEach(node -> {
            // 根据id查询区域
            RegionEntity region = regionService.getById(node.getRegionId());
            node.setRegion(region);
            // 根据id查询商圈
            BusinessTypeEntity businessType = businessTypeService.getById(node.getBusinessId());
            node.setBusinessType(businessType);
            Long count = vendingMachineService.selectCountByNodeId(node.getId());
            node.setVmCount(count);
        });
        return Pager.build(p1);
        // return pager;
    }


    @Override
    public List<VendingMachineEntity> vmListByNodeId(Long nodeId) {
        LambdaQueryWrapper<VendingMachineEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VendingMachineEntity::getNodeId, nodeId);
        return vendingMachineService.list(queryWrapper);
    }

    @Override
    public boolean addNode(NodeReq nodeReq) {
        // 1. 业务校验（商圈是否存在、区域是否存在、点位名是否重复）
        BusinessTypeEntity businessType = businessTypeService.getById(nodeReq.getBusinessId());
        if (ObjectUtil.isNull(businessType)) {
            throw new LogicException("商圈不存在");
        }
        RegionEntity region = regionService.getById(nodeReq.getRegionId());
        if (ObjectUtil.isNull(region)) {
            throw new LogicException("区域不存在");
        }
        // 根据点位名称查询
        LambdaQueryWrapper<NodeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NodeEntity::getName, nodeReq.getName());
        NodeEntity nodeEntity = this.getOne(queryWrapper);
        if (ObjectUtil.isNotNull(nodeEntity)) {
            throw new LogicException("点位名称重复");
        }
        // 2. 保存数据库
        nodeEntity = BeanUtil.toBean(nodeReq, NodeEntity.class);

        // 3. 返回boolean结果
        return save(nodeEntity);

    }

    @Override
    public boolean updateNode(Long id, NodeReq nodeReq) {
        // 1. 业务校验（商圈是否存在、区域是否存在、点位名是否重复）
        BusinessTypeEntity businessType = businessTypeService.getById(nodeReq.getBusinessId());
        if (ObjectUtil.isNull(businessType)) {
            throw new LogicException("商圈不存在");
        }
        RegionEntity region = regionService.getById(nodeReq.getRegionId());
        if (ObjectUtil.isNull(region)) {
            throw new LogicException("区域不存在");
        }
        // 根据点位名称查询
        LambdaQueryWrapper<NodeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NodeEntity::getName, nodeReq.getName());
        // 把自己排除   ne==not equals
        queryWrapper.ne(NodeEntity::getId, id);
        NodeEntity nodeEntity = this.getOne(queryWrapper);
        if (ObjectUtil.isNotNull(nodeEntity)) {
            throw new LogicException("点位名称重复");
        }
        // 2. 修改数据库
        nodeEntity = BeanUtil.toBean(nodeReq, NodeEntity.class);
        nodeEntity.setId(id);

        // 3. 返回boolean结果
        return updateById(nodeEntity);
    }

    @Override
    public boolean deleteNode(Long id) {

        // 判断点位下是否有售货机
        if (vendingMachineService.selectCountByNodeId(id) > 0) {
            throw new LogicException("点位下有售货机，不能删除");
        }

        return removeById(id);
    }
}
